package es.us.lsi.aws.api.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import es.us.lsi.aws.api.model.BasicMessage;
import es.us.lsi.aws.api.model.SocialAccount;
import es.us.lsi.aws.api.server.controllers.ExceptionController;

public class UtilController {

	public static void responseWithJsonObject(HttpServletRequest req,
			HttpServletResponse res, Object obj) {
		Gson gson = new Gson();
		String json = gson.toJson(obj);
		try {
			res.getWriter().print(json);
		} catch (IOException e) {
			ExceptionController.processError(req, res, e);
		}
	}

	public static <T> Object extractObjectFromRequest(HttpServletRequest req,
			Class<T> clazz) throws IOException {
		Object obj = null;
		Gson gson = new Gson();
		StringBuilder sb = new StringBuilder();
		BufferedReader br = req.getReader();

		String jsonString;
		while ((jsonString = br.readLine()) != null) {
			sb.append(jsonString);
		}
		jsonString = sb.toString();

		obj = gson.fromJson(jsonString, clazz);

		return obj;
	}

	public static BasicMessage getMessageFromRequestParam(HttpServletRequest req, HttpServletResponse res) throws ParseException {

		BasicMessage basicMessage = null;
		String pStrText = req.getParameter("text");
		String pDateToPublish = req.getParameter("datetime");
		//2013-05-18T00:00
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//	    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
	    cal.setTime(sdf.parse(pDateToPublish.replace('T',' ')));
	    //magic, do not touch. heuristic reasoning
	    cal.add(Calendar.HOUR_OF_DAY, -2);
	    
		String[] pLstSocialAccount = req.getParameterValues("lstSocialAccount");

		try {
			List<SocialAccount> lstSocialAccount = new ArrayList<SocialAccount>();
			for (String str : pLstSocialAccount) {
				String[] strSplitted = str.split(":");				
				SocialAccount sAccount = new SocialAccount();
				sAccount.setSocialNetwork(strSplitted[0]);
				sAccount.setName(strSplitted[1]);
				
				lstSocialAccount.add(sAccount);
			}
			basicMessage = new BasicMessage(pStrText,lstSocialAccount,cal.getTimeInMillis());
		} catch (Exception e) {
			ExceptionController.processError(req, res, e);
			System.out.println("Error recuperando Basic Message: ");
		}

		return basicMessage;
	}

}
